class Scheduler {
  constructor(limit) {
    this.taskQueue = []
    this.curRun = 0
    this.limit = limit
  }
  addTask(delay, order) {
    let task = function () {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log(order);
          resolve()
        }, delay)
      })
    }
    this.taskQueue.push(task)
  }
  runTask() {
    if (this.curRun < this.limit && this.taskQueue.length > 0) {
      this.curRun++
      this.taskQueue.shift()().then(() => {
        this.curRun--
        this.runTask()
      })
    }
  }
  start() {
    for (let i = 0; i < this.limit; i++) {
      this.runTask()
    }
  }
}

let s = new Scheduler(2)
s.addTask(1000, "1")
s.addTask(500, "2")
s.addTask(300, "3")
s.addTask(400, "4")
s.start()